package com.ptu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ptu.spzx.common.exception.ptuException;
import com.ptu.spzx.common.log.annotation.Log;
import com.ptu.spzx.manager.mapper.SysDeptUserMapper;
import com.ptu.spzx.manager.mapper.SysRoleUserMapper;
import com.ptu.spzx.manager.mapper.SysUserMapper;
import com.ptu.spzx.manager.service.SysUserService;
import com.ptu.spzx.manager.utils.BeanCopyUtils;
import com.ptu.spzx.model.dto.system.AssginDeptDto;
import com.ptu.spzx.model.dto.system.AssginRoleDto;
import com.ptu.spzx.model.dto.system.LoginDto;
import com.ptu.spzx.model.dto.system.SysUserDto;
import com.ptu.spzx.model.entity.system.SysUser;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.spzx.model.vo.system.LoginVo;
import com.ptu.spzx.model.vo.system.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {
        @Autowired
        private SysUserMapper sysUserMapper ;

        @Autowired
        private RedisTemplate<String , String> redisTemplate ;

        @Autowired
        private SysRoleUserMapper sysRoleUserMapper;

        @Autowired
        private SysDeptUserMapper sysDeptUserMapper;

        @Override
        public LoginVo login(LoginDto loginDto) {

            //获取输入的验证码和存储到Redis的Key的名称
            String captcha = loginDto.getCaptcha();
            String key = loginDto.getCodeKey();
            //2，根据redis里面的key查询到redis里面存储的验证码
            String redisCode = redisTemplate.opsForValue().get("user:validate" + key);
            //3，比较输入的验证码和redis里面存储的验证码是否一致
            if(StrUtil.isEmpty(redisCode)||!StrUtil.equalsIgnoreCase(redisCode,captcha)) {
                //4 如果不一样，提示用户校验失败
                throw new ptuException(ResultCodeEnum.VALIDATECODE_ERROR);
            }
            //5， 如果校验一致，删除redis里面的验证码
            redisTemplate.delete("user:validate" + key);
            // 根据用户名查询用户
            SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
            if(sysUser == null) {
//                throw new RuntimeException("用户名或者密码错误") ;
                throw new ptuException(ResultCodeEnum.LOGIN_ERROR);
            }

            // 验证密码是否正确
            String inputPassword = loginDto.getPassword();
            String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
            if(!md5InputPassword.equals(sysUser.getPassword())) {
//                throw new RuntimeException("用户名或者密码错误") ;
                throw new ptuException(ResultCodeEnum.LOGIN_ERROR);
            }

            // 生成令牌，保存数据到Redis中
            String token = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set("user:login" + token , JSON.toJSONString(sysUser) , 30 , TimeUnit.MINUTES);

            // 构建响应结果对象
            LoginVo loginVo = new LoginVo() ;
            loginVo.setToken(token);
            loginVo.setRefresh_token("");

            // 返回
            return loginVo;
        }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login"+token);
    }
    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //用户添加
    @Override
    public void saveSysUser(SysUser sysUser) {
        //判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser abSysUser = sysUserMapper.selectByUserName(userName);
        if(abSysUser!=null){
            throw new ptuException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //输入密码
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);
        //设置statue的值
        sysUser.setStatus(1);
        sysUserMapper.save(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    @Log(title = "用户分配角色",businessType = 0)
    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //根据用户id删除之前的数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());
        //重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        for(Long roleId:roleIdList){
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        }
    }

    @Log(title = "用户分配部门",businessType = 0)
    @Transactional
    @Override
    public void doAssignDept(AssginDeptDto assginDeptDto) {
        //根据用户id删除之前的数据
        sysDeptUserMapper.deleteByUserId(assginDeptDto.getUserId());
        System.out.println("我来到了这里");
        //重新分配新数据
        List<Integer> deptIdList = assginDeptDto.getDeptIdList();
        for(Integer deptId:deptIdList){
            sysDeptUserMapper.doAssign(assginDeptDto.getUserId(),deptId);
        }
    }
}
